package top.korori.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.korori.common.exception.BizException;
import top.korori.common.model.PageData;
import top.korori.common.model.PageParam;
import top.korori.entity.SysRoleUser;
import top.korori.entity.SysUser;
import top.korori.entity.bo.SysUserBo;
import top.korori.entity.vo.SysUserVo;
import top.korori.mapper.SysUserMapper;
import top.korori.service.SysRoleUserService;
import top.korori.service.SysUserService;

import java.util.List;

/**
 * 
 * 后台用户 服务实现类
 * 
 *
 * @author korori
 * @since
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleUserService sysRoleUserService;


    @Override
    public SysUser getByUserNameOrEmailOrPhone(String userName) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.or().eq(SysUser::getUserName,userName);
        queryWrapper.or().eq(SysUser::getEmail,userName);
        queryWrapper.or().eq(SysUser::getPhone,userName);
        return this.getOne(queryWrapper);
    }

    @Override
    public PageData<SysUser> list(SysUser sysUser, PageParam pageParam) {

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ObjUtil.isNotEmpty(sysUser.getUserName()), SysUser::getUserName,sysUser.getUserName());
        queryWrapper.eq(ObjUtil.isNotEmpty(sysUser.getSex()), SysUser::getSex,sysUser.getSex());
        queryWrapper.like(ObjUtil.isNotEmpty(sysUser.getPhone()), SysUser::getPhone,sysUser.getPhone());
        queryWrapper.eq(ObjUtil.isNotEmpty(sysUser.getStatus()), SysUser::getStatus,sysUser.getStatus());

        Page<SysUser> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        Page<SysUser> sysUserPage = this.page(page, queryWrapper);
        PageData<SysUser> pageData = new PageData<>();
        pageData.setTotal(sysUserPage.getTotal());
        pageData.setList(sysUserPage.getRecords());
        return pageData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysUserBo sysUserBo) {
        verifyUser(sysUserBo);
        SysUser sysUser = BeanUtil.copyProperties(sysUserBo, SysUser.class);
        this.save(sysUser);
        handeRoleId(sysUser.getUserId(),sysUserBo.getRoleIds());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(SysUserBo sysUserBo) {
        if (ObjUtil.isEmpty(sysUserBo.getUserId())){
            return;
        }
        verifyUser(sysUserBo);
        SysUser sysUser = BeanUtil.copyProperties(sysUserBo, SysUser.class);
        this.updateById(sysUser);
        sysRoleUserService.delByUserId(sysUserBo.getUserId());
        handeRoleId(sysUser.getUserId(),sysUserBo.getRoleIds());

    }

    private void handeRoleId(Long userId, List<Long> roleIds) {
        if (ObjUtil.isEmpty(roleIds)){
            return;
        }
        SysRoleUser sysRoleUser = new SysRoleUser();
        roleIds.forEach(roleId -> {
            sysRoleUser.setId(null);
            sysRoleUser.setRoleId(roleId);
            sysRoleUser.setUserId(userId);
            sysRoleUserService.save(sysRoleUser);
        });
    }

    @Override
    public SysUserVo get(Long userId) {
        SysUser sysUser = this.getById(userId);
        SysUserVo sysUserVo = BeanUtil.copyProperties(sysUser, SysUserVo.class);
        List<Long> roleIds = sysRoleUserService.getRoleIdsByUserId(userId);
        sysUserVo.setRoleIds(roleIds);
        return sysUserVo;
    }

    private void verifyUser(SysUserBo sysUserBo){

        if (ObjectUtil.isNotEmpty(sysUserBo.getPhone()) && !Validator.isMobile(sysUserBo.getPhone())){
            BizException.cast("请输入正确的手机号");
        }
        if (ObjectUtil.isNotEmpty(sysUserBo.getEmail()) && !Validator.isEmail(sysUserBo.getEmail())){
            BizException.cast("请输入正确的邮箱");
        }

        SysUser sysUser = baseMapper.checkUserUnique(sysUserBo);
        if (ObjectUtil.isNotNull(sysUser)){
            if (ObjectUtil.equals(sysUser.getUserName(),sysUserBo.getUserName())){
                BizException.cast("用户名已存在");
            }
            if (ObjectUtil.equals(sysUser.getPhone(),sysUserBo.getPhone())){
                BizException.cast("手机号已存在");
            }
            if (ObjectUtil.equals(sysUser.getEmail(),sysUserBo.getEmail())){
                BizException.cast("邮箱已存在");
            }
        }


    }

}
